using AutoMapper;
using B.S.NewMedical.Api.Read.Application.Command.ContentManagement.Department;
using B.S.NewMedical.Api.Read.DTOS.Department;
using B.S.NewMedical.Domain.Doctor;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Read.Application.Handler.ContentManagement.Department
{
    /// <summary>
    /// 根据ID获取科室详情处理器
    /// </summary>
    public class GetDepartmentByIdHandler : IRequestHandler<GetDepartmentByIdCommand, ApiResult<DepartmentDisplayDto>>
    {
        private readonly IBaseRepository<DepartmentModel> _departmentRepository;
        private readonly ILogger<GetDepartmentByIdHandler> _logger;
        private readonly IMapper _mapper;

        public GetDepartmentByIdHandler(
            IBaseRepository<DepartmentModel> departmentRepository,
            ILogger<GetDepartmentByIdHandler> logger,
            IMapper mapper)
        {
            _departmentRepository = departmentRepository ?? throw new ArgumentNullException(nameof(departmentRepository));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
            _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
        }

        /// <summary>
        /// 处理根据ID获取科室详情请求
        /// </summary>
        public async Task<ApiResult<DepartmentDisplayDto>> Handle(GetDepartmentByIdCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始查询科室详情，科室ID：{DepartmentId}", request.DepartmentId);

                // 查询科室信息
                var department = await _departmentRepository.GetValue(request.DepartmentId);

                if (department == null || department.IsDeleted)
                {
                    _logger.LogWarning("科室不存在或已被删除，科室ID：{DepartmentId}", request.DepartmentId);
                    return new ApiResult<DepartmentDisplayDto>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "科室不存在或已被删除"
                    };
                }

                // 获取父级科室信息（如果是二级科室）
                string? parentDepartmentName = null;
                if (department.ParetId > 0)
                {
                    try
                    {
                        var parentDepartment = await _departmentRepository.GetValue(department.ParetId);
                        parentDepartmentName = parentDepartment?.DepartmentName;
                    }
                    catch (Exception ex)
                    {
                        _logger.LogWarning(ex, "查询父级科室信息失败，父级科室ID：{ParentId}", department.ParetId);
                        // 父级科室查询失败不影响主流程，继续执行
                    }
                }

                // 映射为DTO
                var departmentDto = _mapper.Map<DepartmentDisplayDto>(department);
                departmentDto.Level = department.ParetId == 0 ? "一级科室" : "二级科室";
                departmentDto.ParentDepartmentName = parentDepartmentName;

                _logger.LogInformation("查询科室详情成功，科室名称：{DepartmentName}", departmentDto.DepartmentName);

                return new ApiResult<DepartmentDisplayDto>
                {
                    Code = ApiEnum.Success,
                    Msg = "查询成功",
                    Data = departmentDto
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询科室详情时发生错误，科室ID：{DepartmentId}", request.DepartmentId);
                return new ApiResult<DepartmentDisplayDto>
                {
                    Code = ApiEnum.Error,
                    Msg = "查询失败"
                };
            }
        }
    }
}